/*审批意见*/

import { useForm } from "../../../framework/common/context/metadata-context";
import { Button, Input, Form, Popover, message as antdMessage, Spin , Tooltip} from "antd";
import { useState } from "react";
import request from "../../../framework/common/utils/request";
import eventBus, { useSubscribe } from "../../../framework/common/eventBus";
import { useUpdate } from "ahooks";
import findIndex from "lodash/findIndex";

import { LoadingOutlined } from "@ant-design/icons";
import clsx from "clsx";

const { TextArea } = Input;


//审批同意表单
export default function ({ approveType, onChange, setFormData, value = "", placeholder = "请输入发起意见", form }) {
  const metadataManager = useForm().root;
  const { data: tplData, urlPrefix, params, getErrors } = metadataManager;

  return (
    <div>
      <Cyyj onChange={onChange} tplData={tplData} approveType={approveType}></Cyyj>
      <TextArea
        showCount={true}
        rows="7"
        maxLength="1000"
        onChange={(val) => {
          onChange(val.target.value);
        }}
        value={value}
        placeholder={placeholder}
      ></TextArea>
    </div>
  );
}
//常用审批意见
function Cyyj({ onChange, tplData, approveType }) {
  const updater = useUpdate();
  useSubscribe(
    "cyyj.update."+approveType,
    () => {
      updater();
    },
    [approveType,updater]
  );

  let opinionList = tplData.__opinionList__?.[approveType] || [];

  return (
    <div className="clearfix pt-1 pb-3 h-[42px]">
      <ul className="cyyj-list table-useful float-left relative z-[1] list-none mb-0">
        {opinionList
          .slice()
          .reverse()
          .slice(0, 3)
          .map((o) => {
            return (
              <Tooltip
                overlayClassName="mytip" placement="bottomLeft" color="white" title={<OpinionTip text={o.common_opinion}></OpinionTip>} overlayStyle={{ maxWidth: "750px" }}
              >
                <li
                  key={o.id}
                  onClick={() => onChange(o.common_opinion)}
                  className=" inline-block leading-6 border border-solid bg-[#f6f9ff] border-[#f6f9ff] hover:border-[#266eff] px-2 mr-[10px] rounded-sm  max-w-[98px] truncate align-middle cursor-pointer text-[#222]"
                >
                  {o.common_opinion}
                </li>
              </Tooltip>
            );
          })}
      </ul>
      <Popover
        destroyTooltipOnHide={true}
        overlayClassName="cyyj-popover"
        placement="bottomRight"
        content={<CyyjContent onChange={onChange} approveType={approveType} opinionList={opinionList}></CyyjContent>}
        title={null}
        trigger="click"
      >
        <button className="float-right cursor-pointer  btn-default btn-ico tipWrap-dom h-[22px] text-color-primary ">
          <i className="mr-1 iconfont icon-shenpiyaodian"></i>常用意见
        </button>
      </Popover>
    </div>
  );
}

//常用意见提示
function OpinionTip({
  text
}){
  return <div className="whitespace-pre-wrap max-w-sm min-w-[98px]" dangerouslySetInnerHTML={{__html: text}}></div>
}

//常用审批输入框
function CyyjInput({ approveType }) {
  const [text, setText] = useState(null);
  return (
    <>
    <div className="mx-[20px] mb-3 mt-2 relative">
      <Form.Item noStyle={true}>
        <TextArea
          className={clsx("textarea-opinion pr-[60px]", text !== null && text.trim() === "" ? "has-error" : null)}
          placeholder="请输入常用意见"
          maxLength={200}
          value={text}
          autoSize={{
            minRows: 1,
            maxRows: 3
          }}
          onChange={(e) => {
            setText(e.target.value);
          }}
        />
        <CyyjAdd approveType={approveType} text={text} setText={setText}></CyyjAdd>
      </Form.Item>
    </div>
    <div className="mx-[20px] mt-3 pb-3 text-[#A5A6AA] text-xs">{text?.length || 0}/200</div>
    </>
  );
}
//常用审批意见添加
function CyyjAdd({ text, setText, approveType }) {
  const metadataManager = useForm().root;
  const { data: tplData, urlPrefix } = metadataManager;
  const [loading, setLoading] = useState(false);
  function handleAdd() {
    if (text === null || text?.trim() === "") {
      setText("");
    } else {
      var data = {
        type: approveType,
        common_opinion: text,
        user_id: tplData.CurUserGUID,
        step_type: tplData.StepInfo.step_type,
        is_end_task: tplData.NodeInfo && tplData.NodeInfo.is_end_task,
      };
      setLoading(true);
      request({
        data: data,
        method: "POST",
        url: "/flowinstance/approval/write-common-opinion",
        noTip: true//请求错误时，axios不展示公共错误
      }).then(
        function (result) {
          if (result.code == 1) {
            antdMessage.success("添加成功");
            tplData.__opinionList__?.[approveType]?.push({ common_opinion: text, id: result.data });
            eventBus.publish("cyyj.update."+approveType);
            setText(null);
            document.querySelector(".content-useful").scrollTop = 0;
          } else {
            antdMessage.error(result.message);
          }
          setLoading(false);
        },
        function (error) {
          antdMessage.error("添加失败");
          setLoading(false);
        }
      );
    }
  }
  return (
    <div className="absolute right-0 top-0 h-full z-10 w-[80px] text-right">
      <Button className="link-button-sm addbtn-opinion text-color-primary" loading={loading} type="link" onClick={handleAdd}>
        添加
      </Button>
    </div>
  );
}
//常用审批意见列表
function CyyjList({ opinionList, onChange, approveType }) {
  const metadataManager = useForm().root;
  const { data: tplData, urlPrefix } = metadataManager;
  const [loading, setLoading] = useState(false);
  function handleDelete(id) {
    setLoading(true);
    request({
      data: { id: id, step_type: tplData.StepInfo.step_type },
      method: "POST",
      url: "/flowinstance/approval/delete-common-opinion",
      noTip: true//请求错误时，axios不展示公共错误
    }).then(
      function (result) {
        if (result.code == 1) {
          antdMessage.success("删除成功");
          let index = findIndex(tplData.__opinionList__?.[approveType], (o) => o.id === id);
          tplData.__opinionList__?.[approveType].splice(index, 1);
          eventBus.publish("cyyj.update."+approveType);
        } else {
          antdMessage.error(result.message);
        }
        setLoading(false);
      },
      function (error) {
        setLoading(false);
        antdMessage.error("删除失败");
      }
    );
  }
  return (
    <div className="overflow-auto content-useful max-h-80 pt-[20px]">
      {opinionList
        .slice()
        .reverse()
        .map((o) => {
          return (
            <div
              key={o.id}
              className="mx-[20px] mb-3 group break-all whitespace-pre-line items-center min-h-[40px] rounded-[4px] px-3 py-2 flex justify-between cursor-pointer border border-solid bg-[#f6f9ff] border-[#f6f9ff] hover:border-[#266eff] relative"
              onClick={() => {
                onChange(o.common_opinion);
              }}
            >
              <span className=" max-w-[320px] text-justify">{o.common_opinion}</span>
              {loading ? (
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                  className="hidden group-hover:block text-color-primary"
                >
                  <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} />
                </span>
              ) : (
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDelete(o.id);
                  }}
                  className="hidden cursor-pointer group-hover:block absolute -right-2 -top-2 z-10 overflow-hidden rounded-full bg-white w-4 h-4 leading-4"
                >
                  <i className="iconfont icon-zhongzhi1 text-color-f86161"></i>
                </span>
              )}
              {/*  */}
            </div>
          );
        })}
    </div>
  );
}
//常用审批内容
function CyyjContent({ opinionList, onChange, approveType }) {
  return (
    <div className="w-[380px]">
      <CyyjList approveType={approveType} onChange={onChange} opinionList={opinionList}></CyyjList>
      <CyyjInput approveType={approveType}></CyyjInput>
    </div>
  );
}

